package service

import (
	"gorm.io/gorm"
	"guns-go/global"
	"guns-go/model"
	"guns-go/model/request"
	"strconv"
)

func SaveRoleDataScope(sysRoleDataScope *model.SysRoleDataScope, tx *gorm.DB) error {
	return tx.Create(sysRoleDataScope).Error
}

func GetRoleDataScopeIdList(roleIds []int) (err error, scopeIds []int) {

	ids := make([]int, 0)

	if len(roleIds) > 0 {

		var userDataScopes []model.SysRoleDataScope
		err = global.GVA_DB.Where("role_id in (?)", roleIds).Find(&userDataScopes).Error

		if err != nil {
			return err, nil
		}

		if len(userDataScopes) > 0 {
			for _, scope := range userDataScopes {
				ids = append(ids, scope.OrgId)
			}
		}
	}

	return err, ids
}

//根据机构id集合删除对应的角色-数据范围关联信息
func DeleteRoleDataScopeListByOrgIdList(orgIdList []int, tx *gorm.DB) error {
	return tx.Delete(model.SysRoleDataScope{}, "org_id in (?)", orgIdList).Error
}

func DeleteRoleDataScopeListByRoleId(roleId int, tx *gorm.DB) error {
	return tx.Delete(model.SysRoleDataScope{}, "role_id = ?", roleId).Error
}

func RoleGrantDataScope(sysRoleParam *request.SysRoleParam, tx *gorm.DB) error {

	roleId := sysRoleParam.Id
	//删除所拥有数据
	err := DeleteRoleDataScopeListByRoleId(roleId, tx)

	if err != nil {
		return err
	}

	//授权数据
	if len(sysRoleParam.GrantOrgIdList) > 0 {

		for _, orgId := range sysRoleParam.GrantOrgIdList {
			roleDataScope := new(model.SysRoleDataScope)
			roleDataScope.RoleId = roleId
			id, _ := strconv.Atoi(orgId)
			roleDataScope.OrgId = id

			err = SaveRoleDataScope(roleDataScope, tx)

			if err != nil {
				return err
			}
		}
	}
	return nil
}
